<?php

class Config extends dbObject {
	public $type;
	public $user_id;
	public $value;
	private static $mObjConfig = array();
	
	public function __construct($type, $uid) {
		$type = strtolower($type);
		$this->dbTable = "config:{$type}";
		$this->tableKey = 'user_id';
		$this->keyType = 'string';
		
		$this->type = $type;
		$this->user_id = $uid;
	}
	
	public function saveConfig($config, $all_users=false) {
		if (is_object($config)) $config = json_encode($config);
		$this->value = $config;
		$this->update();
		
		if ($all_users) {
			// overwrite the config for all users in the user's org
			$user = new InsightUser($this->user_id);
			$users = CIOrg::getUsers($user->org_id);
			
			foreach ($users as $uid) {
				$cfg = new Config($this->type, $uid);
				$cfg->saveConfig($config);
			}
		}
	}
	
	public function getConfig() {
		// 1. Check the static cache
		if (isset(Config::$mObjConfig[$this->type])) {
			return Config::$mObjConfig[$this->type]->fields;
		}

		$this->readConfig();
		return Config::$mObjConfig[$this->type]->fields;
	}

	public function getLists() {
		// 1. Check the static cache
		if (isset(Config::$mObjConfig[$this->type])) {
			return Config::$mObjConfig[$this->type]->lists;
		}
		
		$this->readConfig();
		return Config::$mObjConfig[$this->type]->lists;
	}
	
	private function readConfig() {
		// 2. Check the database
		$this->find($this->user_id);
		$db_config = json_decode($this->value);
		if (isset($db_config)) {
			Config::$mObjConfig[$this->type] = $db_config;
		}

		// 3. Use the standard config lists
		else {
			$d = json_decode(file_get_contents(dirname(__FILE__)."/../config/{$this->type}.json"));
			Config::$mObjConfig[$this->type] = $d;
		}
		
		$user = new InsightUser($this->user_id);
		Config::$mObjConfig[$this->type]->fields = $user->describeConfig($this->type, Config::$mObjConfig[$this->type]->fields);
	}
	
}

?>